import { useRef, useEffect } from "react"
import * as echarts from "echarts"
import Session from "../Session"
import "./index.css"
import { Button, Popover } from "antd"
import { useLayoutEffect } from "react"
import * as am4core from "@amcharts/amcharts4/core"
import * as am4charts from "@amcharts/amcharts4/charts"
import am4themes_material from "@amcharts/amcharts4/themes/material"

// import am4themes_kelly from "@amcharts/amcharts4/themes/kelly"

am4core.useTheme(am4themes_material)

const option = (dataX, dataY) => ({
  // title: {
  //   text: '整体进度跟踪',  // 标题文本
  //   left: 0      // 位置居中
  // },

  tooltip: {
    trigger: "item"
  },
  grid: {
    top: "10%",
    left: "2%",
    right: "6%",
    bottom: "10%",
    containLabel: true
  },

  xAxis: {
    type: "category",
    data: dataX,
    axisLine: {
      lineStyle: {
        opacity: 0.1 // 半透明轴线
      }
    },
    axisTick: {
      alignWithLabel: true,
      show: false
    },
    axisLabel: {
      // X轴标签样式
      fontSize: 12 // 字体大小（px）
    },
    boundaryGap: false
  },
  yAxis: {
    type: "value"
    // axisLabel: {  // X轴标签样式
    //   fontSize: 16  // 字体大小（px）
    // },
    // interval: 25,
    // max: 100
  },
  series: [
    {
      data: dataY,
      type: "line",
      smooth: true,
      symbol: "circle",
      symbolSize: 12,
      itemStyle: {
        color: "#1E5EF8",
        borderColor: "#ffffff",
        borderWidth: 4
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: "rgba(58, 77, 233, 0.8)" }, // 顶部颜色
          { offset: 1, color: "rgba(58, 77, 233, 0.1)" } // 底部颜色
        ])
      },
      lineStyle: {
        // color: '#1E5EF8',
        width: 5,
        type: "solid",
        color: {
          type: "linear",
          x: 0, // 从左到右渐变
          y: 0,
          x2: 1,
          y2: 0,
          colorStops: [
            { offset: 0, color: "#2f63e7" }, // 左侧蓝色
            // { offset: 0.4, color: '#1890ff' }, // 保持蓝色
            { offset: 0.5, color: "#07b7fc" }, // 中间白色
            // { offset: 0.6, color: '#1890ff' }, // 恢复蓝色
            { offset: 1, color: "#2f63e7" } // 右侧蓝色
          ]
        }
      }
    }
  ]
})

// const pieOption = (data = []) => ({

//   // title: {
//   //   text: 'Referer of a Website',
//   //   subtext: 'Fake Data',
//   //   left: 'center'
//   // },
//   tooltip: {
//     trigger: 'item',
//     formatter: function(params) {
//     return `
//       <div style="font-weight:bold">${params.name}</div>
//       <div>数值: ${params.value}</div>
//       <div>占比: ${params.percent}%</div>
//     `;
//   }
//   },
//   legend: {
//     bottom:  0,
//     left: 'center',
//     orient: 'horizontal',
//         // 文字样式设置
//     textStyle: {
//       color: '#333',      // 文字颜色
//       fontSize: 10,       // 文字大小
//       fontWeight: 'bold', // 文字粗细
//       fontFamily: 'Arial' // 字体
//     },

//     // 颜色块(icon)设置
//     itemWidth: 10,        // 图例标记的图形宽度
//     itemHeight: 10,       // 图例标记的图形高度
//     itemGap: 6          // 图例每项之间的间隔
//   },

//   series: [
//     {
//       type: 'pie',
//       radius: '70%',
//       data,
//           label: {
//       show: false // 完全隐藏标签（包括文字和指示线）
//     },
//       emphasis: {
//         itemStyle: {
//           shadowBlur: 10,
//           shadowOffsetX: 0,
//           shadowColor: 'rgba(0, 0, 0, 0.5)'
//         }
//       }
//     }
//   ]
// })

const AuditStatistics = ({ progress = {}, overview = "", status = {} }) => {
  const mainChart = useRef(null)
  const overviewChart = useRef(null)

  // 添加默认数据
  const defaultProgress = {
    months: ["1月", "2月", "3月", "4月", "5月", "6月"],
    completion_rate: [30, 40, 50, 60, 75, 85]
  }

  const defaultStatus = {
    completed: { count: 15 },
    in_progress: { count: 8 },
    not_started: { count: 5 }
  }

  // 添加默认概述文本
  const defaultOverview =
    "公司积极响应审计意见，按时完成整改工作。截至目前，已有75%的整改事项完成，其余项目按计划推进中。相关部门建立了长效机制，确保问题不再发生。管理层高度重视审计发现问题的根源分析，采取系统性措施提升内控水平，整改效果显著。各项整改举措实施后，相关业务流程运行更加规范高效，有效防范了经营风险。"

  // 当API未返回数据时使用默认数据
  const {
    months = defaultProgress.months,
    completion_rate: completeRates = defaultProgress.completion_rate
  } = progress && Object.keys(progress).length > 0 ? progress : defaultProgress

  // 使用overview或默认概述文本
  const overviewText = overview || defaultOverview

  const createOverviewChart = () => {
    // 使用status或默认值
    const statusData =
      status && Object.keys(status).length > 0 ? status : defaultStatus

    // console.log("status", statusData, Object.entries(statusData))
    const dataToShow = []
    Object.entries(statusData).forEach((item) => {
      const [key, data] = item
      if (key === "completed") {
        dataToShow.push({
          name: "已完成",
          value: data.count,
          color: "#76da91"
          // color: data.color
        })
      } else if (key === "in_progress") {
        dataToShow.push({
          name: "进行中",
          value: data.count,
          // color: data.color
          color: "#63b2ee"
        })
      } else if (key === "not_started") {
        dataToShow.push({
          name: "未开始",
          value: data.count,
          // color: data.color
          color: "#f8cb7f"
        })
      }
    })

    const chart = am4core.create("result", am4charts.PieChart3D)
    overviewChart.current = chart
    chart.paddingTop = 10
    chart.legend = new am4charts.Legend()
    // 图例配置
    chart.legend = new am4charts.Legend()
    chart.legend.position = "top"
    chart.legend.width = 180
    chart.legend.height = am4core.percent(40)
    // chart.legend.contentAlign = "left";
    // chart.legend.scrollable = true;
    // 创建图表后配置绘图区域
    chart.radius = am4core.percent(120) // 半径占可用空间的70%

    // 图例标记样式
    chart.legend.markers.template.width = 12
    chart.legend.markers.template.height = 12
    // chart.legend.markers.template.marginRight = 8;
    chart.legend.itemContainers.template.paddingTop = 4
    chart.legend.itemContainers.template.paddingBottom = 4

    // 图例文本样式
    chart.legend.labels.template.fontSize = 12
    chart.legend.labels.template.fill = am4core.color("#333")
    // chart.legend.labels.template.truncate = true;
    // chart.legend.labels.template.fullWords = false;
    // chart.legend.labels.template.maxWidth = 60;

    chart.legend.paddingBottom = 30

    // 图例外边距
    // chart.legend.marginLeft = 20;
    // chart.legend.marginRight = 20;
    // chart.legend.marginTop = 10;

    chart.hiddenState.properties.opacity = 0 // this creates initial fade-in

    chart.data = dataToShow.map((item) => ({
      val: item.value,
      name: item.name
    }))
    chart.angle = 60
    chart.depth = 10
    chart.fontSize = 12
    chart.tooltip.label.fontSize = 12
    chart.logo.disabled = true
// 
    const series = chart.series.push(new am4charts.PieSeries3D())
    series.dataFields.value = "val"
    series.dataFields.category = "name"
    series.colors.list = dataToShow.map((item) => am4core.color(item.color))
    series.labels.template.disabled = true

    // series.ticks.template.stroke = am4core.color("#000000");
    series.ticks.template.strokeOpacity = 0.8

    // 使指示线颜色与对应饼块一致
    series.ticks.template.adapter.add("stroke", function (fill, target) {
      if (target.dataItem && target.dataItem.slice) {
        return target.dataItem.slice.fill
      }
      return fill
    })

    // series.slices.template.adapter.add("fill", function(fill, target) {
    //   // 获取自动分配的基础颜色
    //   const baseColor = target.dataItem.color;

    //   // 创建径向渐变
    //   const gradient = new am4core.RadialGradient();
    //   gradient.addColor(am4core.color(am4core.colors.brighten(baseColor.rgb, 0.2)), 0); // 中心亮色
    //   gradient.addColor(am4core.color(am4core.colors.brighten(baseColor.rgb, -0.3)), 0.8); // 边缘暗色

    //   return gradient;
    // });

    series.radius = am4core.percent(110)

    series.labels.template.html = `<div><div>{value}</div><div>{category}</div></div>`
    series.slices.template.states.getKey("active").properties.distance = 20 // 分离距离
    series.slices.template.states.getKey(
      "active"
    ).properties.shiftDistance = 1.6 // 3D高度变化
  }

  useLayoutEffect(() => {
    createOverviewChart()
    return () => {
      overviewChart.current.dispose()
    }
  }, [])

  const myMainChart = useRef(null)
  useEffect(() => {
    if (mainChart.current) {
      if (!myMainChart.current) {
        myMainChart.current = echarts.init(mainChart.current)
      }
      myMainChart.current.setOption(option(months, completeRates))
    }
  }, [completeRates, months])

  return (
    <Session
      title="四、审计整改"
      style={{
        backgroundImage: `url('right_banner_1.png')`,
        backgroundRepeat: "no-repeat",
        backgroundSize: "cover",
        width: "914px",
        height: "257px"
      }}
    >
      <div className="flex mx-4">
        <div className="flex-1">
          <h3 className="text-lg font-bold mt-3 mb-2">整改情况</h3>
          <main className="flex items-center">
            <div className="h-full text-sm text-[#414141] ">
              <Popover
                content={<p className="w-[400px]">{overviewText}</p>}
                placement="top"
              >
                <p className="w-full line-clamp-6">{overviewText}</p>
              </Popover>
            </div>
          </main>
        </div>
        <div
          className="w-[200px] h-[180px]  flex items-center justify-center"
          id="result"
        >
          {/* <div className="inner"></div>
          <div className='z-10'><span className='text-[26px] font-bold mr-1'>100</span><span>%</span></div> */}
        </div>
        <div className="w-3/5 pl-4">
          <h3 className="text-lg font-bold mt-3">整改进度跟踪</h3>
          <div ref={mainChart} className="w-full h-[160px]"></div>
        </div>
      </div>
    </Session>
  )
}

export default AuditStatistics
